//服务器地址
import {server} from '../config/index.js';

castapp.init();

var $telephotoEle = $('#telephoto');  //电话号码输入框
var $count = $('.count');  //倒计时

var userInfo = localStorage.getItem('userInfo');
userInfo = userInfo? JSON.parse(userInfo): {};
$telephotoEle.val(userInfo.telephone);

//点击获取验证码
var timer = null;  //定时器
var telephotoNum = null;  //手机号
var code_num = null;  //验证码
//点击获取验证码
$('.register-yzm-btn').get(0).addEventListener('tap',function(e){
	e.preventDefault();
	//是否可以发送
	var canSend = $(this).hasClass('public-g-g-btn');
	if(!canSend){
		return;
	}
	var telephoto_num = $input.eq(1).val().trim();
	if(!telephoto_num){
		castapp.prompt('请输入手机号');
		return;
	}
	if(!/^1\d{10}$/g.test(telephoto_num)){
		castapp.prompt('请输入正确的手机号');
		return;
	}
	//获得随机数，默认为4位，可知道位数
	code_num = castapp.getIdCode();
	
	//请求短信接口
	var url_api = server+ '/api/sms';
	$.ajax({
		url: server+ '/api/sms',
		type:'post',
		data:{
			telephoto: telephoto_num,
			code_num
		},
		success:function(res){
			//console.log(res)
			if(res.msg == 'Has'){  //该号码已被注册
				castapp.prompt('该号码已被注册');
				clearInterval(timer);
				timer = null;
				$('.register-yzm-btn').addClass('public-g-g-btn');
				$count.fadeOut(1);
				return;
			}
			castapp.prompt('发送成功');
			telephotoNum = telephoto_num;
			$('.register-yzm-btn').removeClass('public-g-g-btn');
			var count = 60;
			$count.fadeIn(1).text('('+count+')');
			if(timer){
				clearInterval(timer);
			}
			timer = setInterval(function(){
				count--;
				if(count>=0){
					$count.text('('+count+')');
				}else{
					clearInterval(timer);
					timer = null;
					$('.register-yzm-btn').addClass('public-g-g-btn');
					$count.fadeOut(1);
				}
			},1000);
		},
		error: function(err){
			castapp.prompt('请求出错,请重新发送');
			$('.register-yzm-btn').addClass('public-g-g-btn');
			$count.fadeOut(1);
		}
	});
});

var $input = $('.mui-input-row input');
//点击确定按钮
$('.login-btn button').get(0).addEventListener('tap', function(e){
	e.preventDefault();
	var telephoto = $telephotoEle.val().trim();  //手机号
	var new_telephone = $input.eq(1).val().trim();
	var yzm_num = $input.eq(2).val().trim();
	
	
	if(!new_telephone){
		castapp.prompt('请输入手机号');
		return;
	}
	if(!/^1\d{10}$/g.test(new_telephone)){
		castapp.prompt('请输入正确的手机号');
		return;
	}
	if(telephoto != telephotoNum){
		castapp.prompt('手机号不能改变');
		return;
	}
	
	if(yzm_num != code_num){
		castapp.prompt('验证码错误');
		return;
	}
	
	
	//发送注册请求
	castapp.ajax({
        //测试地址
		url: server+ '/api/user/change_telephone',
		type:'post',
		data:{
		    'telephone': telephone,
		    nickname: userInfo.nickname,
		    new_telephone: new_telephone
		},
		succFn:function(res){
			res = JSON.parse(res);
			if(res.msg=='OK'){
				castapp.prompt('修改成功');
			    castapp.newInterface({
					url: './account_secure.html',
					id: 'account_secure'
				});
				//关闭当前界面
				castapp.closeCurrentInterface();
			}
		},
		errFn:function(data){
		    castapp.prompt('服务错误,请稍后再试')
		}
	});
});